#
# "@(#) $Id: LibraryViewItem.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
from Player import *
from Utils.human import *
from CheckListViewItem import *
from TrackViewItemObject import *
from RatingMenu import *
from Utils.Paths import *
from DB.Library import *
from Utils.utils import *
from Utils.crushToAscii import *
import time

def _get(a,b):
	if a==None: return b
	return a

_star = None

def star():
	global _star
	if _star==None:
		_star = QPixmap(art("labelstar.png"))
	return _star


_playingIcon = None
def playingIcon():
	global _playingIcon
	if _playingIcon==None:
		_playingIcon = QPixmap(art("labelcurrentplaying.png"))
	return _playingIcon

_pausedIcon = None

def pausedIcon():
	global _pausedIcon
	if _pausedIcon==None:
		_pausedIcon = QPixmap(art("labelcurrentpause.png"))
	return _pausedIcon

_noIcon = None

def noIcon() :
	global _noIcon
	if _noIcon==None:
		_noIcon = QPixmap()
	return _noIcon

class LibraryViewItem(ListViewItem):
	def __init__(self,container,track,columns=[1,2,3,4,5,6,7,8]):
		ListViewItem.__init__(self,container)
		self._track = track
		self.trackItem = TrackViewItemObject(self)
		self.status = 'idle'
		self.setDragEnabled(True)
		self.columns=columns
		self.setColumnIndices()
		self.loadTrackInfo()
		self.dummyKey = QString(" ")

	def die(self):
		#print "item dying"
		if self.trackItem:
			self.trackItem.trackItem = None
			self.trackItem = None
			
	def setColumnIndices(self):
		colCtr=0
		if self.columns[0]:
			colCtr+=1
			self.titleColumn = colCtr
		else: self.titleColumn=self.columns[0]
		if self.columns[1]:
			colCtr+=1
			self.durationColumn = colCtr
		else: self.durationColumn=self.columns[1]
		if self.columns[2]:
			colCtr+=1
			self.artistColumn =colCtr
		else: self.artistColumn=self.columns[2]
		if self.columns[3]:
			colCtr+=1
			self.albumColumn = colCtr
		else: self.albumColumn=self.columns[3]
		if self.columns[4]:
			colCtr+=1
			self.genreColumn = colCtr
		else: self.genreColumn=self.columns[4]
		if self.columns[5]:
			colCtr+=1
			self.ratingColumn = colCtr
		else: self.ratingColumn=self.columns[5]
		if self.columns[6]:
			colCtr+=1
			self.playCountColumn =colCtr
		else: self.playCountColumn=self.columns[6]
		if self.columns[7]:
			colCtr+=1
			self.playDateColumn = colCtr
		else: self.playDateColumn=self.columns[7]
			
##
##	def setColumnIndices(self):
##		self.titleColumn = 1
##		self.durationColumn = 2
##		self.artistColumn = 3
##		self.albumColumn = 4
##		self.genreColumn = 5
##		self.ratingColumn = 6
##		self.playCountColumn = 7
##		self.playDateColumn = 8
##		self.setRenamableItems()
	
	def track(self):
		return self._track

	def loadTrackInfo(self):
		#start = time.ti me()
		self.loadTitle()
		self.loadDuration()
		self.loadArtistAlbum()
		self.loadGenre()
		self.loadRating()
		self.loadPlayCount()
		self.loadPlayDate()
		#self.loadEnabled()
		#self.loadPlayIcon()
		#end = time.time()
		#print "loaded LibraryViewItem",self._track.title,"in",end-start,"seconds"
	
	#def loadEnabled(self):
		#self.setOn(self._track.enabled)
	
	#def setOn():
	#	pass
		#font=QFont
		#font.setItalic()
		#self.setFont(font)
	
		

	def loadPlayIcon(self):
		self.setPlayingIcon()
	
	def loadTitle(self):
		if self.titleColumn:
			self.setText(self.titleColumn,_get(self._track.title,'<No name>'))
			self.titleKey = QString(self._track.titleKey())
		#self.setText(self.titleColumn,_get(self._track.title,'<No name>'))
		#self.titleKey = QString(self._track.titleKey())
	
	def loadDuration(self):
		if self.durationColumn:
			self.setText(self.durationColumn,humanDuration(self._track.totalTime))
			self.durationKey = QString(self._track.durationKey())
		#self.setText(self.durationColumn,humanDuration(self._track.totalTime))
		#self.durationKey = QString(self._track.durationKey())
	
	def loadArtistAlbum(self):
		if self.artistColumn:
			self.setText(self.artistColumn,_get(self._track.artist,''))
			self.artistKey = 'A%s' % self._track.artistKey()
		if self.albumColumn:
			self.setText(self.albumColumn,_get(self._track.album,''))
			self.albumKey = 'A%s' % self._track.albumKey()
			self.albumKey = unikode(self.albumKey)+unikode(self._track.discTrackKey())
		if self.albumColumn and self.artistColumn:
			self.artistKey = unikode(self.artistKey)+unikode(self.albumKey)
			self.artistKey = QString(self.artistKey)
			self.albumKey = QString(self.albumKey)
		#self.setText(self.artistColumn,_get(self._track.artist,''))
		#self.artistKey = 'A%s' % self._track.artistKey()
		#self.setText(self.albumColumn,_get(self._track.album,''))
		#self.albumKey = 'A%s' % self._track.albumKey()
		#self.albumKey = unikode(self.albumKey)+unikode(self._track.discTrackKey())
		#self.artistKey = unikode(self.artistKey)+unikode(self.albumKey)
		#self.artistKey = QString(self.artistKey)
		#self.albumKey = QString(self.albumKey)
	
	def loadGenre(self):
		if self.genreColumn:
			self.setText(self.genreColumn,_get(self._track.genre,''))
			self.genreKey = QString(self._track.genreKey())
		#self.setText(self.genreColumn,_get(self._track.genre,''))
		#self.genreKey = QString(self._track.genreKey())
	
	def loadRating(self):
		if self.ratingColumn:
			self.rating = self._track.rating # drawn specially
			if self.rating: self.ratingKey = QString(self.rating)
			else: self.ratingKey = QString(0)
			self.setText(self.ratingColumn,'')
##		if self.ratingColumn:
##			self.rating = self._track.rating # drawn specially
##			if self.rating: self.ratingKey = QString(self.rating)
##			else: self.ratingKey = QString(0)
##			self.setText(self.ratingColumn,'')
##	
	def loadPlayCount(self):
		if self.playCountColumn:
			self.playCountKey = self._track.playCount
			if self.playCountKey:
				self.setText(self.playCountColumn,str(self.playCountKey))
			else:
				self.setText(self.playCountColumn,"")
				self.playCountKey = 0
			self.playCountKey = QString("%06d" % self.playCountKey)
	
	def loadPlayDate(self):
		if self.playDateColumn:
			self.setText(self.playDateColumn,humanTimeStamp(self._track.playDate))
			if self._track.playDate: self.playDateKey = QString("%010d" % time.mktime(self._track.playDate))
			else: self.playDateKey = QString("")
		
	def setRenamableItems(self):
		self.setRenameEnabled(self.titleColumn,True)
		self.setRenameEnabled(self.artistColumn,1)
		self.setRenameEnabled(self.albumColumn,1)
		
	def setPlayingIcon(self):
		global noIcon
		status = self._track.playStatus
		if self.status!=status:
			if status=='playing':
				self.setPixmap(0,playingIcon())
			elif status=='paused':
				self.setPixmap(0,pausedIcon())
			else:
				self.setPixmap(0,noIcon())
			self.status = status

	def key(self,column,ascending):
		#print "hit LibraryView key",column
		try:
			if column==self.titleColumn:
				return self.titleKey
			elif column==self.durationColumn:
				return self.durationKey
			elif column==self.artistColumn:
				return self.artistKey
			elif column==self.albumColumn:
				return self.albumKey
			elif column==self.genreColumn:
				return self.genreKey
			elif column==self.ratingColumn:
				return self.ratingKey
			elif column==self.playCountColumn:
				return self.playCountKey
			elif column==self.playDateColumn:
				return self.playDateKey
		except: pass
		return "0"

	def okRename(self,column):
		oldValue = unikode(self.text(column))
		ListViewItem.okRename(self,column)
		newValue = unikode(self.text(column))
		if oldValue!=newValue:
			newValue = newValue.strip()
			if column==self.titleColumn:
				if len(newValue)==0:
					KMessageBox.error(None,i18n("Track title must not be empty"),i18n("Bad Track Title"))
					self.setText(self.titleColumn,oldValue)
					self.startRename(self.titleColumn)
				else:
					self._track.loadTagsFrom({'title':newValue})
			elif column==self.artistColumn:
				self._track.loadTagsFrom({'artist':newValue})
			elif column==self.albumColumn:
				self._track.loadTagsFrom({'album':newValue})
			elif column==self.genreColumn:
				self._track.loadTagsFrom({'genre':newValue})

	def trackID(self):
		return self._track.trackID

	def contentsMouseDoubleClickEvent(self,event):
		self.play()

	def play(self):
		playlist = self.listView().playlist
		self._track.play(playlist)
	'''	
	def stateChange(self,value):
		self._track.enabled = bool(value)
	'''
	def changedAttribute(self,attribute,oldValue,newValue):
		#print "changed",attribute,"from",oldValue,"to",newValue
		if attribute =='title': self.loadTitleInfo()
		elif attribute=='totalTime': self.loadDuration()
		elif attribute in ['artist','album','trackNum','discNum']: self.loadArtistAlbum()
		elif attribute=='rating':
			self.loadRating()
			self.repaint()
		elif attribute=='contentType': self.loadGenre()
		elif attribute=='playCount': self.loadPlayCount()
		elif attribute=='playDate': self.loadPlayCount()
		#elif attribute=='enabled': self.loadEnabled()
		elif attribute=='playStatus': self.setPlayingIcon()
	
	def paintCell(self,p,cg,column,width,alignment):
		#ListViewItem.paintCell(self,p,cg,column,width,alignment)
		try:
			cg=QColorGroup(cg)
			if column==self.ratingColumn and self.rating: # rating column
				for i in xrange(0,self.rating):
					p.drawPixmap(QPoint(i*13+3,2),star())
			
			if(self._track.playStatus=='playing' or self._track.playStatus=='paused'):
                                cg.setColor(QColorGroup.Text,QColor(0,0,217))
                                cg.setColor(QColorGroup.Base,QColor(230,230,230))
				#p.save()
				font=QFont(p.font())
				font.setPointSize(font.pointSize()+3)
				#font.setWeight(90)
				#font.setBold(True)
				#self.paintCell(self,p,cg,column,width,alignment)
				#p.restore()

			elif(not self._track.enabled):
	
				'''
				p.save()
				font=p.font()
				ont.setItalic
				self.paintCell(p,)
				p.restore()
				'''
				cg.setColor(QColorGroup.Text,QColor(150,150,150))
			#FIXME bold the current playing song
			#if(self._track.playStatus=='playing' or self._track.playStatus=='paused'):
			#	p.save()
			#	font=QFont(p.font())
                        #        font.setBold()
				
			QListViewItem.paintCell(self,p,cg,column,width,alignment)
			#p.restore()

		except: pass

	def clickedRatingAt(self,px):
		if self.isSelected():
			stars = ((px-3)/13)+1
			if stars<0:
				stars = 0
			elif stars>5:
				stars = 5
			self._track.loadTagsFrom({'rating':stars})

	def getInfo(self):
		trackIDs = self.listView().selectedTrackIDs()
		if trackIDs and len(trackIDs)>0:
			if len(trackIDs)==1:
				self._track.getInfo()
			else:
				self.listView().getMultiInfoForTrackIDs(trackIDs)
	
	def pause(self):
		self._track.pause()
	
	def showFile(self):
		self._track.showLocation()
	
	def resetPlayCount(self):
		tracks = self.listView().selectedTracks()
		for track in tracks:
			track.playCount = 0
	
	
	def enable(self):
		self.doEnable(True)
		
	def disable(self):
		self.doEnable(False)
	
	def doEnable(self,enable):
		tracks = self.listView().selectedTracks()
		for track in tracks:
			track.enabled = enable

	def reload(self):
		try: self._track.setFile(self._track.location)
		except: pass
		
	def moveToTrash(self):
		library = Library.mainLibrary()
		trash = library.playlistWithName("Trash")
		trackIDs = self.listView().selectedTrackIDs()
		#print "moving",trackIDs,"to",trash
		trash.addTrackIDs(trackIDs)
		#print "removing tracks from all playlists"
		library.removeTrackIDsFromAllPlaylists(trackIDs)

	def contextMenu(self,pos,col):
		menu = QPopupMenu()
		self.addContextMenuItems(menu)
		item = menu.exec_loop(pos)
	
	def addContextMenuItems(self,menu):
		self.addStandardContextMenuItems(menu)
		self.addCustomContextMenuItems(menu)
	
	def addStandardContextMenuItems(self,menu):
		status = self._track.playStatus
		if status=='playing':
			menu.insertItem(i18n("Pause"),self.pause)
		else:
			menu.insertItem(i18n("Play"),self.play)
		menu.insertItem(i18n("Get Info..."),self.getInfo)
		menu.insertItem(i18n("Show Song File"),self.showFile)
		menu.insertItem(i18n("Reload Tags from File"),self.reload)
		menu.insertItem(i18n("Reset Play Count"),self.resetPlayCount)
		menu.ratingMenu = LRatingMenu()
		menu.insertItem(i18n("Rating"),menu.ratingMenu)
		menu.ratingMenu.setRating(self._track.rating)
		QObject.connect(menu.ratingMenu,PYSIGNAL("setRating"),self.setRating)
		menu.insertSeparator()
		makeSep = False
		artist = _get(self._track.artist,None)
		if artist!=None and len(artist):
			makeSep = True
			artistText=str.join("",["Create Playlist for \"",artist,"\""])
			menu.insertItem(i18n(str(artistText)),self.createArtistPlaylist)
		album = _get(self._track.album,None)
		if album!=None and len(album):
			makeSep = True
			albumText=str.join("",["Create Playlist for \"",album,"\""])
			menu.insertItem(i18n(str(albumText)),self.createAlbumPlaylist)
		if makeSep: menu.insertSeparator()
		if artist!=None and len(artist):
			menu.insertItem(i18n("Look up  this Artist in Wikipedia"),self.lookupArtist)
			menu.insertSeparator()
		menu.insertItem(i18n("Enable"),self.enable)
		menu.insertItem(i18n("Disable"),self.disable)
	
	def setRating(self,rating):
		self._track.loadTagsFrom({'rating':rating})

	def addCustomContextMenuItems(self,menu):
		menu.insertItem(i18n("Move to Trash"),self.moveToTrash)
	
	def createArtistPlaylist(self):
		if self._track.artist:
			self.listView().createArtistPlaylist(unikode(self._track.artist))
	
	def createAlbumPlaylist(self):
		if self._track.album:
			self.listView().createAlbumPlaylist(unikode(self._track.album))
	
	def lookupArtist(self):
		if self._track.artist:
			artist = KURL.encode_string_no_slash( crush(self._track.artist) )
			url = QString( "http://en.wikipedia.org/wiki/%1" ).arg(artist )
			os.system("konqueror \"%s\" &" % (unikode(url)))

